#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "proto.h"


int main(int argc, char * argv[])
{
    int sd;
    struct msg_st * sbufp;
    struct sockaddr_in raddr;
    char ipstr[IPSTRSIZE];
    size_t size;

    if(argc < 3)
    {
        fprintf(stderr, "argc < 2\n");
        exit(0);
    }

    if(strlen(argv[2]) > NAMEMAX)
    {
        fprintf(stderr, "name too long\n");
        exit(0);
    }

    size = sizeof(struct msg_st) + strlen(argv[2]);
    sbufp = malloc(size);
    if(sbufp == NULL)
    {
        perror("malloc");
        exit(0);
    }

    sd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sd < 0)
    {
        perror("socket");
        exit(1);
    }

    strcpy(sbufp->name, argv[2]);
    sbufp->math = htonl(rand()%100);
    sbufp->chinese = htonl(rand()%100);

    raddr.sin_family = AF_INET;
    inet_pton(AF_INET, argv[1], &raddr.sin_addr);
    raddr.sin_port = htons(atoi(RCVPORT));

    if(sendto(sd, sbufp, size, 0, (void *)&raddr, sizeof(raddr)) < 0)
    {
        perror("sendto");
        exit(1);
    }
    puts("ok");

    close(sd);

    exit(0);
}